<template>
	<view class="container hidden pdlr">
		<view class="fl user-info mgb">
			<view class="mgr">
				<image class="avatar" :src="userInfo.avatarUrl" mode="aspectFill"></image>
			</view>
			<view class="">
				<view class="nickname mgb">用户</view>
				<view class="tag red">女</view>
			</view>
		</view>
		<view class="title mgb">基本信息</view>
		<view class="cardview bgwhite pd mgb">
			<view class="fl mgb10">
				<text class="form-tit">入学时间:</text>
				<text class="form-value">2025-09-01</text>
			</view>
			<view class="fl mgb10">
				<text class="form-tit">学 号:</text>
				<text class="form-value">2207240121</text>
			</view>
			<view class="fl mgb10">
				<text class="form-tit">身份证号:</text>
				<text class="form-value">610102xxxxxxxx1234</text>
			</view>
			<view class="fl">
				<text class="form-tit">手机号码:</text>
				<text class="form-value">12345678910</text>
			</view>
		</view>
		<view class="title mgb">打卡进度</view>
		<view class="cardview bgwhite pd mgb">
			<view >
				<view :class="['fl-rsb']">
					<view class="setting-icon" style="width: 90%;">
						<view class="fl-rsb">
							<text>已打卡</text>
							<view><text>2</text>/<text>6</text></view>
						</view>
						<view class="bline-list mgt mgb5">
							<view class="bline"  v-for="item in 6" :key="item"></view>
						</view>
					</view>
					<view class="fl-rr"  style="width: 10%;">
						<uni-icons type="right" color="#333" size="16"></uni-icons>
					</view>
				</view>
			</view>
		</view>
		<view class="title mgb">功能模块</view>
		<view class="pdlr pdt pdb5 mgt bgwhite bdr4 settingList w100">
			<view v-for="(item,index) in settingList" :key="index">
				<view :class="['fl-rsb pdb', index == (settingList.length - 1) ? '' : 'mgb bd1s']"
					@click="handleItemClick(item)">
					<view class="fl setting-icon">
						<view :class="['iconfont', item.icon ]" :style="{color: item.color ,fontSize:'22px'}"></view>
						<view class="mgl10">{{item.label}}</view>
					</view>
					<view class="fl-rr">
						<uni-icons type="right" color="#333" size="16"></uni-icons>
					</view>
				</view>
			</view>
		</view>
		<view class="float-area fl-cc">
			<view class="" style="width: 90%;">
				<view class="btn btn-primary" plain @click="logout">
					<view class="fl">
						<view class="iconfont icon-tuichu mgr5" style="color:#f53837; font-size: 16px;"></view>
						<text>退出登录</text>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		reactive,
		onMounted,
		computed,
		nextTick
	} from 'vue';
	import {
		useStore
	} from '@/ya/store';
	import router from "@/ya/router/index.js";
	import Layout from '@/components/Layout.vue';
	const userStore = useStore('user');
	// 当前用户信息
	// const userInfo = computed(() => parseInt(userStore.userInfo));
	// 响应式状态
	const userInfo = reactive({
		avatarUrl: 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0', // 默认头像地址
		nickName: ''
	});
	const isLoading = ref(false);

	// 获取用户信息处理函数
	const handleGetUserInfo = (e) => {
		if (isLoading.value) return;

		isLoading.value = true;

		// 处理用户授权
		if (e.detail.userInfo) {
			// 用户允许授权，保存信息
			userInfo.value = e.detail.userInfo;

			sendUserInfoToServer(e.detail.userInfo);

			uni.showToast({
				title: '获取成功',
				icon: 'success'
			});
		} else {
			// 用户拒绝授权
			uni.showModal({
				title: '提示',
				content: '您拒绝了授权，将无法获取您的微信信息',
				showCancel: false
			});
		}

		isLoading.value = false;
	};

	// 模拟发送用户信息到服务器
	const sendUserInfoToServer = (userInfo) => {
		console.log('发送用户信息到服务器:', userInfo);
	};
	const handleLogin = async () => {
		if (isLoading.value) return;
		isLoading.value = true;

		try {
			// 检查网络连接
			const networkRes = await uni.getNetworkType();
			if (networkRes.networkType === 'none') {
				uni.showToast({
					title: '请检查网络连接',
					icon: 'none'
				});
				return;
			}

			// 获取用户基础信息（包含签名）
			const wxRes = await this.getUserProfile();
			console.log('基础信息rawData:', wxRes);
			// 获取登录凭证code
			const {
				code
			} = await this.getLoginCode();
			// 组合用户信息和code发送到服务端
			if (!code) {
				throw new Error('获取登录凭证失败');
			}
			console.log('loginRes', loginRes);
			const result = await this.sendLoginRequest(code);
			console.log('sendLoginRequest', result);
			// 保存登录状态和用户信息
			uni.setStorageSync('token', result.token);
			uni.showToast({
				title: '登录成功'
			});
			// 把openId，头像，昵称一起存进用户资料；
		} catch (error) {
			console.error('微信登录失败:', error);
			uni.showToast({
				title: '登录失败，请重试',
				icon: 'none'
			});
		} finally {
			isLoading.value = false;
		}
	};
	const sendLoginInfoToServer = (data) => {
		return new Promise((resolve, reject) => {
			uni.request({
				url: 'https://your-api.com/auth/login', // 替换为你的服务端登录接口
				method: 'POST',
				data,
				success: (res) => {
					if (res.data.code === 200) {
						resolve(res.data.data);
					} else {
						reject(new Error(res.data.message || '登录失败'));
					}
				},
				fail: (err) => {
					reject(err);
				}
			});
		});
	};
	// 选择头像回调
	const onChooseAvatar = (e) => {
		// 更新头像地址
		userInfo.avatarUrl = e.detail.avatarUrl;
	};
	// 微信登录流程
	const onWxLogin = async (e) => {
		if (this.loading) return;
		this.loading = true;
		try {
			// 获取登录凭证code
			const {
				code
			} = await this.getLoginCode();
			// 组合用户信息和code发送到服务端
			const result = await this.sendLoginRequest(code);
			console.log('sendLoginRequest', result);
			// 保存登录状态和用户信息
			uni.setStorageSync('token', result.token);
			uni.showToast({
				title: '登录成功'
			});
			// 获取用户基础信息（包含签名）
			const wxRes = await this.getUserProfile();
			console.log('基础信息rawData:', wxRes);

		} catch (error) {
			console.error('微信登录失败:', error);
			uni.showToast({
				title: '登录失败，请重试',
				icon: 'none'
			});
		} finally {
			this.loading = false;
		}
	};

	// 获取用户信息
	const getUserProfile = () => {
		return new Promise((resolve, reject) => {
			uni.getUserProfile({
				desc: '用于完善个人信息',
				success: (res) => resolve(res),
				fail: (err) => reject(err)
			});
		});
	};

	// 获取登录凭证code
	const getLoginCode = () => {
		return new Promise((resolve, reject) => {
			uni.login({
				provider: 'weixin',
				success: (res) => {
					console.log('getLoginCode', res);
					resolve(res)
				},
				fail: (err) => reject(err)
			});
		});
	};
	// 发送登录请求到服务端
	const sendLoginRequest = async (code) => {
		const res = await uni.request({
			url: 'http://192.168.1.37:19010/api/wx/login',
			method: 'get',
			data: {
				code
			}
		});
		if (res.data.code === 200) {
			return res.data.data;
		} else {
			throw new Error(res.data.message || '登录接口异常');
		}
	};
	// 用户类型
	const userType = computed(() => parseInt(userStore.userType));
	// 登录类型
	const loginType = computed(() => parseInt(userStore.loginType));
	// 动态处理个人中心列表
	const settingList = ref([{
			label: '常见问题',
			url: '/pages/mine/myMark',
			icon: 'icon-wdsc',
			color: "#FFC300"
		},
		{
			label: '帮助中心',
			url: '/pages/mine/notice',
			icon: 'icon-xtgg',
			color: "#EE89DF"
		},
	]);
	// 记录当前打开的选项
	const cutItem = ref(settingList.value[0]);
	const popupRef = ref(null);
	// 修改手机号码
	const onSettingList = (item) => {
		cutItem.value = item;
		popupRef.value.open('bottom');
	};
	const closedPopup = () => {
		popupRef.value.close();
	};
	const shouldShowItem = computed(() => {
		return (item) => {
			if (item.formConfig.type === 'navTo') {
				return loginType.value === 3 && userType.value === 99;
			}
			return true;
		};
	})
	const change = () => {

	};
	const submit = () => {

	};
	onMounted(async () => {
		await nextTick();
		// 初始化设置默认值
		cutItem.value = settingList.value[0];
	})
	const logout = async () => {
		// 登出
		// await userStore.logout().then(()=>{
		uni.redirectTo({
			url: '/pages/login/login'
		})
		// });
	};
	const handleItemClick = (item) => {
		router.go(item.url);
	};

	function desensitizeIdCard(idCard) {
		if (idCard && idCard.length === 18) {
			return idCard.slice(0, 6) + '*'.repeat(8) + idCard.slice(-4);
		}
		return idCard;
	}
</script>

<style lang="scss" scoped>
	.container {
		background-color: none !important;
		height: calc(100vh - 100rpx);
		background-size: 100% 50%;
		background-repeat: no-repeat;
	}

	.pup-con {
		padding-bottom: 5rem;
	}

	.user-ava {
		width: 80px;
		height: 80px;
		background-color: #f2f2f2;
		border-radius: 50%;
		padding: 0px;
		box-shadow: 0 4px 12px rgb(0 0 0 / 5%);
	}

	.setting-icon .iconfont {
		font-size: 18px !important;
	}

	.settingList .bd1s {
		border-bottom-color: #f2f2f2;
	}

	.mineInfoCard {
		opacity: 1;
		padding: 20px 0px;
		border-radius: 20px;
		background: rgba(255, 255, 255, 0.17);
		box-shadow: 0px 2px 37px rgba(0, 0, 0, 0.09);
		backdrop-filter: blur(25px);
		color: #FFF;
	}

	.mine-label {
		font-size: 14px;
	}

	.mine-value {
		font-size: 20px;
		font-weight: 500;
	}

	.container {
		height: 100vh;
		padding: 20px;
	}

	.user-info {
		display: flex;
		flex-direction: column;
		align-items: center;
		margin-bottom: 20px;
		margin-top: 80rpx;
	}

	.avatar {
		width: 80px;
		height: 80px;
		border-radius: 50%;
		box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
	}

	.nickname {
		font-size: 18px;
		margin-bottom: 10px;
		font-weight: 500;
	}

	.no-user-info {
		margin-bottom: 40px;
		text-align: center;
	}

	.tips {
		font-size: 16px;
		color: #FFF;
	}

	.get-info-btn {
		width: 200px;
		height: 44px;
		line-height: 44px;
		background-color: #07C160;
		color: #fff;
		border-radius: 22px;
		font-size: 16px;
		border: none;
	}

	.get-info-btn[disabled] {
		background-color: #cccccc;
	}

	.form-tit {
		margin-right: 10px;
		width: 85px;
	}
	.bline{
		height: 5px;
		border-radius: 5px;
		width: 100%;
		background-color: #07C160;
	}
	.bline-list{
		display: grid;
		grid-template-rows: 1fr;
		grid-template-columns: 1fr 1fr 1fr 1fr 1fr 1fr;
		gap: 3px;
	}
</style>